﻿using ContributionDeposit.CoreFrontEnd;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Models.DataModel;
using System.Threading.Tasks;
using PagedList;
using PagedList.Mvc;
using System.Data;
using System.IO;

namespace ContributionDeposit.Controllers
{
    //[Authorize]
    public class UserAccountController : Core_FrontEnd
    {
        
        //
        // GET: /UserAccount/
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult ListUserAccount(string searchtext,int? page)
        {
            CheckUserLogin = CheckLogin();
            if(CheckUserLogin == true)
            {
                try
                {
                    int pageNum = (page ?? 1);
                    var lstUserAccount = fun_db.GetlstUserAccount().ToList();
                    ViewBag.SearchText = searchtext;
                    if (!string.IsNullOrEmpty(searchtext))
                        lstUserAccount = lstUserAccount.Where(c => c.UserName.ToUpper().Contains(searchtext.ToUpper())).ToList();
                    return View(lstUserAccount.ToPagedList(pageNum, 10));
                }
                catch
                {
                    return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.AbsoluteUri });
                }
            }
            return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.AbsoluteUri });
        }
        public ActionResult AddUser()
        {
            CheckUserLogin = CheckLogin();
            if(CheckUserLogin == true)
            {
                ViewBag.lstGroupUser = new SelectList(fun_db.GetlstGroupUser().ToList(), GroupUser.s_GourpUserId, GroupUser.s_GroupName);
                return View();
            }
            return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.AbsoluteUri });
        }
        [HttpPost]
        public async Task<ActionResult> AddUser(UserAccount objUser, bool Activevalue)
        {
            if (ModelState.IsValid)
            {
                var acc = fun_db.GetlstUserAccount().Where(c => c.UserName == objUser.UserName).ToList();
                if(acc.Count == 0)
                {
                    if (Activevalue == true)
                        objUser.Active = true;
                    else
                        objUser.Active = false;
                    int result = await fun_db.AddUser(objUser);
                    if (result == 1)
                    {
                        return RedirectToAction("ListUserAccount");
                    }
                }
                else
                {
                    ViewBag.Usernamematch = "Username have been uesd ! ";
                    ViewBag.lstGroupUser = new SelectList(fun_db.GetlstGroupUser().ToList(), GroupUser.s_GourpUserId, GroupUser.s_GroupName);
                    return View();
                }
            }
            return View();
        }
        public ActionResult Edituser(Guid UserId)
        {
            CheckUserLogin = CheckLogin();
            if(CheckUserLogin == true)
            {
                var objUser = fun_db.GetObjUser(UserId);
                ViewBag.lstGroupUser = new SelectList(fun_db.GetlstGroupUser().ToList(), GroupUser.s_GourpUserId, GroupUser.s_GroupName);
                return View(objUser);
            }
            return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.AbsoluteUri });
        }
        [HttpPost]
        public async Task<ActionResult> EditUser(UserAccount ObjUser, bool Activevalue)
        {
            if (ModelState.IsValid)
            {
                if (Activevalue == true)
                    ObjUser.Active = true;
                else
                    ObjUser.Active = false;
                if(Session["user"] != null)
                {
                    ObjUser.ModifiedBy = fun_db.GetObjUserByUsername(Session["user"].ToString()).UserAccountID;
                }
                int result = await fun_db.EditUser(ObjUser);
                return RedirectToAction("ListUserAccount");
            }
            return View();
        }
        public ActionResult ChangePass(Guid UserId)
        {
            var objUser = fun_db.GetObjUser(UserId);
            return View(objUser);
        }
        [HttpPost]
        public async Task<ActionResult> ChangePass(UserAccount ObjUser, string OldPassword)
        {
            CheckUserLogin = CheckLogin();
            if (CheckUserLogin == true)
            {
                if (ModelState.IsValid)
                {
                    int CheckPass = fun_db.CheckPassUser(ObjUser, OldPassword);
                    if(CheckPass == 1)
                    {
                        int result = await fun_db.ChangPassUser(ObjUser);
                        if (result == 1)
                            return RedirectToAction("ChangePassSuccess");
                    }
                    else
                    {
                        ViewBag.Error = "PassWord is not valid";
                    }
                }
                return View();
            }
            return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.AbsoluteUri });
        }
        public ActionResult ChangePassSuccess()
        {
            CheckUserLogin = CheckLogin();
            if (CheckUserLogin == true)
            {
                return View();
            }
            return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.AbsoluteUri });
        }
        public async Task<ActionResult> DeleteUser(string UserId)
        {
            try
            {
                string[] arrId = UserId.Split('|');
                if(arrId.Length > 1)
                {
                    for (int i = 0; i < arrId.Length - 1; i++)
                    {
                        Guid _GroupId = Guid.Parse(arrId[i]);
                        int result = await fun_db.DeleteUser(_GroupId);
                    }
                }
                else
                {
                    int result = await fun_db.DeleteUser(Guid.Parse(UserId));
                    if (result == 1)
                    {
                        return RedirectToAction("ListUserAccount");
                    }
                    return RedirectToAction("ListUserAccount");
                }
                return RedirectToAction("ListUserAccount");
            }
            catch
            {

            }
            return Json("Fail", JsonRequestBehavior.AllowGet);
        }
        public ActionResult ExportUserAccount()
        {
            var fileName = string.Format("{0} {1}.xlsx", ControllerContext.RouteData.Values["controller"].ToString(), DateTime.Now.ToString("yyyyMMdd HHmmss"));

            string filepath = AppDomain.CurrentDomain.BaseDirectory + "App_Data/ExcelFiles/" + fileName;
            DataTable dt = Utilities.Utility.ConvertToDataTable(fun_db.GetlstUserAccount().ToList());

            Utilities.Utility.WriteDataTableToExcel(dt, Path.GetFileNameWithoutExtension(fileName), filepath, "Details");
            byte[] filedata = System.IO.File.ReadAllBytes(filepath);
            string contentType = MimeMapping.GetMimeMapping(filepath);

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = fileName,
                Inline = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());
            System.IO.File.Delete(filepath);
            return File(filedata, contentType);
        }
    }
}